package com.xiguthings.xiniu.iot.post.poster;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.xiguthings.xiniu.iot.common.PostData;
import com.xiguthings.xiniu.iot.post.common.entity.PostResult;
import com.xiguthings.xiniu.iot.post.controller.DataPostContrller;

@Component
public class PostCenter {
	private final Logger LOGGER = LoggerFactory.getLogger(PostCenter.class);

	private Map<String, PostDataBuffer> postDataBuffers = new HashMap<>();

	@Autowired
	private DataPostContrller dataPostContrller;
	@Autowired
	private SendPostThreadPool sendPostThreadPool;

	@Value("${handle.buffer.thread.pool.size}")
	private int addBufferThreadPoolSize;

	private ExecutorService addBufferThreadPool;

	/**
	 * post发送数据
	 *
	 * @param postData
	 */
	public void postData(PostData postData) {
		if (postData.getBatchSize() > 1) {
			if (addBufferThreadPool == null) {
				addBufferThreadPool = Executors.newFixedThreadPool(addBufferThreadPoolSize);
			}
			// 批量发送
			PostDataBuffer postDataBuffer = getPostDataBuffer(postData);
			addBufferThreadPool.execute(new Runnable() {
				@Override
				public void run() {
					// TODO Auto-generated method stub
					postDataBuffer.add(postData);// 加入缓冲区
				}
			});
		} else {
			// 单条发送
			sendPostThreadPool.executeSendPost(postData);
		}
	}

	/**
	 * 提交post发送的结果
	 */
	public void postResult(PostResult result) {
		dataPostContrller.recordResultPost(result);
	}

	/**
	 * 再次尝试发送数据
	 *
	 * @param data
	 */
	public void tryPostAgain(PostData data) {
		dataPostContrller.tryPostAgain(data);
	}

	/**
	 * 获取缓冲对象
	 * 
	 * @param postData
	 * @return
	 */
	private synchronized PostDataBuffer getPostDataBuffer(PostData postData) {
		PostDataBuffer postDataBuffer = postDataBuffers.get(postData.getUrl());
		if (postDataBuffer == null) {
			postDataBuffer = new PostDataBuffer(postData.getInterval(), postData.getBatchSize(), postData.getUrl(),
					sendPostThreadPool);
			postDataBuffers.put(postData.getUrl(), postDataBuffer);
		}
		return postDataBuffer;
	}
}
